package crud

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ UserRolesModel = (*customUserRolesModel)(nil)

type (
	// UserRolesModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUserRolesModel.
	UserRolesModel interface {
		userRolesModel
		DeleteByUserId(ctx context.Context, userId int64) error
		FindAllByUserId(ctx context.Context, userId int64) ([]*UserRoles, error) // 新增方法声明
	}

	customUserRolesModel struct {
		*defaultUserRolesModel
	}
)

// NewUserRolesModel returns a model for the database table.
func NewUserRolesModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserRolesModel {
	return &customUserRolesModel{
		defaultUserRolesModel: newUserRolesModel(conn, c, opts...),
	}
}

// FindAllByUserId 查询指定用户ID的所有角色关联
func (m *customUserRolesModel) FindAllByUserId(ctx context.Context, userId int64) ([]*UserRoles, error) {
	var userRoles []*UserRoles
	query := fmt.Sprintf("select %s from %s where `user_id` = ?", userRolesRows, m.table)
	err := m.QueryRowsNoCacheCtx(ctx, &userRoles, query, userId)
	if err != nil {
		return nil, err
	}
	return userRoles, nil
}


// DeleteByUserId 删除指定用户ID的所有角色关联
func (m *customUserRolesModel) DeleteByUserId(ctx context.Context, userId int64) error {
	// 调用函数查询该用户的所有角色关联
	userRoles, err := m.FindAllByUserId(ctx, userId)
	if err != nil {
		return err
	}

	// 构建要清除的缓存键
	keys := make([]string, 0, len(userRoles)*2)
	for _, ur := range userRoles {
		idKey := fmt.Sprintf("%s%v", cacheSmileSunshineUserUserRolesIdPrefix, ur.Id)
		userRoleKey := fmt.Sprintf("%s%v:%v", cacheSmileSunshineUserUserRolesUserIdRoleIdPrefix, ur.UserId, ur.RoleId)
		keys = append(keys, idKey, userRoleKey)
	}

	// 执行删除操作并清除缓存
	_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where `user_id` = ?", m.table)
		return conn.ExecCtx(ctx, query, userId)
	}, keys...)

	return err
}
